package com.vast.ui.component.socket.observers;

import org.eclipse.core.runtime.ListenerList;

import com.vast.ui.component.protocol.Protocol;
import com.vast.ui.component.socket.listener.IReceiveListener;
import com.vast.ui.component.socket.listener.ISocketConnectionListener;
import com.vast.ui.component.socket.models.Request;
import com.vast.ui.component.socket.state.Sequence;
import com.vast.ui.component.util.ConsoleLoggerSingleton;
import com.vast.ui.component.util.Logger;

public class DecodeRequester {
	private final String        pluginId;
	private final Sequence      sequence;
	private final ListenerList  receiveListenerList;
	private final ListenerList  socketConnectionListenerList;
	private final Logger        logger;
	
	public DecodeRequester(String pluginId, Sequence sequence) {
		this.pluginId      = pluginId;
		this.sequence      = sequence;
        this.receiveListenerList = new ListenerList();
		this.socketConnectionListenerList = new ListenerList();
        this.logger        = ConsoleLoggerSingleton.getInstance();
	}
	
	public void addSocketConnectionListener(ISocketConnectionListener listener){
		logger.writeEntry(pluginId + ": addSocketConnectionListener :" + listener.toString());
		socketConnectionListenerList.add(listener);
	}
	
	public void removeSocketConnectionListener(ISocketConnectionListener listener){
		logger.writeEntry(pluginId + ": removeSocketConnectionListener :" + listener.toString());
		socketConnectionListenerList.remove(listener);
	}
	
	public void addReceiveListener(IReceiveListener listener){
		receiveListenerList.add(listener);
	}
	
	public void removeReceiveListener(IReceiveListener listener){
		receiveListenerList.remove(listener);
	}
	
	public void startup(){
		//new Thread(this).start();
	}
	
	public void decodeRequest(Request request) {
		if (request.command == Protocol.PK_SOCKET_TERMINATE) {
			logger.writeEntry(pluginId + ": PK_SOCKET_TERMINATE");
			Object[] listeners = socketConnectionListenerList.getListeners();
			for (Object listener : listeners) {
				((ISocketConnectionListener) listener).notifyStateChange(sequence);
			};
			return;
		}
		
		Object[] listeners = receiveListenerList.getListeners();
		for (Object listener : listeners) {
			((IReceiveListener) listener).received(request);
		}
	}

}
